﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MiniFox.Web.Configurations;
using MiniFox.Web.Middlewares;

namespace MiniFox.Web.AppStarting
{
    /// <summary>
    /// 
    /// </summary>
    internal class RegisterMiddleware : HttpStartBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="hostEnvironment"></param>
        /// <param name="webConfiguration"></param>
        public RegisterMiddleware(IConfiguration configuration, IWebHostEnvironment hostEnvironment, WebConfiguration webConfiguration) : base(configuration, hostEnvironment, webConfiguration)
        {
        }

        List<Type> _middlewares;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="middleTypes"></param>
        protected virtual void LoadBuiltInMiddlewares(List<Type> middleTypes)
        {
            middleTypes.Add(typeof(CrossDomainMiddleware));
            middleTypes.Add(typeof(WebWatcherMiddleware));
        }
        /// <summary>
        /// 
        /// </summary>
        public List<Type> MiddlewareTypes
        {
            get
            {
                if (_middlewares == null)
                {
                    _middlewares = new List<Type>();
                    LoadBuiltInMiddlewares(_middlewares);
                    if (this.WebConfiguration != null && this.WebConfiguration.Middlewares != null)
                        foreach (var providerSetting in WebConfiguration.Middlewares)
                        {
                            Type type = providerSetting;
                            _middlewares.Add(type);
                        }
                }
                return _middlewares;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public override void OnServicesConfiguring(IServiceCollection services)
        {
            this.MiddlewareTypes.ForEach(type => services.AddTransient(type));

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public override void OnApplicationConfiguring(IApplicationBuilder app)
        {
            this.MiddlewareTypes.ForEach(type => app.UseMiddleware(type));
        }
    }
}
